<template>
  <div class="dynamicForm">
    <el-dialog
      width="60%"
      class="previewModel"
      v-model="dialogVisible"
      draggable
      destroy-on-close
      :title="rollUpConfig.title"
      :close-on-click-modal="false"
    >
      <div id="dynamic-form"></div>
    </el-dialog>
  </div>
</template>
<script setup lang="tsx">
import { ref, nextTick, createApp, reactive, onMounted, watch, onBeforeUnmount } from "vue";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import ElementPlus from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import type { FormRules, FormInstance } from "element-plus";
import SInput from "@/components/SInput.vue";
import SSelect from "@/components/SSelect.vue";
import TreeSelect from "@/components/STree.vue";
import Upload from "@/components/Upload/Img.vue";
import { storeToRefs } from "pinia";
import { useGlobalStore } from "@/stores/modules/global";
import { useDynamicStore } from "@/stores/modules/dynamic";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useCatalogStore } from "@/stores/modules/catalog";
import ACrypto from "@/utils/crypto";
import { transTree } from "@/utils/util";
import { useRoute } from "vue-router";
import { FormRuler } from "../../ts/FormRule";
import RuleClass from "../../ts/FieldRule";
import useCurrentInstance from "@/utils/useCurrentInstance";
import global from "@/utils/SnowflakeClass";
import vueAxios from "@/api/index";

const { proxy } = useCurrentInstance();
const props = defineProps({
  rollUpConfig: {
    type: Object,
    default: () => {
      return {};
    }
  }
});
// 路由
const route = useRoute() as any;
// 窗体显示与否
const dialogVisible = ref(false);
// pinia数据
const globalStore = useGlobalStore();
const dynamicStore = useDynamicStore();
const dictionryStore = useDictionryStore();
const catalogStore = useCatalogStore();
// 配置
const visibleConfig = ref<any>({});
// 打开弹出框,挂接动态表单
const open = () => {
  proxy.$vueAxios
    .get("MasterBaseFormModelTable/GetInitialize", {
      fmtId: props.rollUpConfig.fmtData.filter((v: any) => v.FMT_ID === route.query.fmtid)[0].FMT_Parent_ID
    })
    .then((res: any) => {
      visibleConfig.value = res.List[0];
      props.rollUpConfig.htmlCode = ACrypto.getSS(props.rollUpConfig.htmlCode);
      dialogVisible.value = true;
      nextTick(() => {
        getDynamicDom();
      });
    });
};
// 挂载动态窗体
// 存储当前挂载的应用实例
let currentApp: any = null;

const getDynamicDom = () => {
  // 如果有之前的实例，先卸载
  if (currentApp) {
    currentApp.unmount();
    currentApp = null;
  }

  // 创建实例
  currentApp = createApp({
    components: {
      SInput,
      TreeSelect,
      Upload,
      SSelect
    },
    setup() {
      // 表单绑定字段
      let modalFormData = props.rollUpConfig.modalFormData;
      // 控制连续提交是否显示
      const { continuousSubmission } = storeToRefs(globalStore);
      // 表单字段规则
      const ruleList = ref([]);
      // 表单验证规则
      let formRules = reactive<FormRules>({});
      formRules = visibleConfig.value.ValidationList.filter((v: any) => v.V_Enable === true);
      const FormRulesClass = new FormRuler(formRules);
      formRules = FormRulesClass.getValidation();
      // 表单实例
      const modalFormRef = ref<FormInstance>();
      // 按钮加载属性
      const submitLoading = ref(false);
      //连续新增按钮加载属性
      const submitLoading2 = ref(false);
      // 字典数据
      const dictionary = dictionryStore.getDictionaryObj;
      // 数据表表名
      const tableName = ref("");
      const init = () => {
        ruleList.value = visibleConfig.value.FieldRule.filter(
          (v: any) => v.FR_Enable === true || v.FR_Rule.toLowerCase().includes("jm")
        );
        tableName.value = visibleConfig.value.FMT.FMT_TableName;
        // 执行字段规则类方法
        const FieldRuleClass = new RuleClass({ modalFormData: modalFormData, ruleList: ruleList.value });
        modalFormData = FieldRuleClass.ReSetEncrypt();
        console.log(ruleList.value, modalFormData);
        if (ruleList.value && ruleList.value.length > 0) {
          const FieldRuleClass = new RuleClass({
            modalFormData: modalFormData,
            ruleList: ruleList.value,
            tableName: tableName.value
          }); // 执行字段规则类方法
          FieldRuleClass.fieldRuleInit();
          console.log("执行init规则后", modalFormData);
        }
      };
      // 取消事件
      const cancel = () => {
        dialogVisible.value = false;
      };
      // 确认事件
      const onSubmit = (type: string) => {
        modalFormRef.value!.validate(valid => {
          if (valid) {
            submitLoading.value = true;
            submitAnalyse(type); // 内部执行逻辑
          } else {
            return false;
          }
        });
      };
      // 确认事件
      const onSubmit2 = (type: string) => {
        modalFormRef.value!.validate(valid => {
          if (valid) {
            submitLoading2.value = true;
            submitAnalyse(type); // 内部执行逻辑
          } else {
            return false;
          }
        });
      };
      // 内部执行逻辑;
      const submitAnalyse = (type: string) => {
        const FieldRuleClass = new RuleClass({ modalFormData: modalFormData, ruleList: ruleList.value }); // 执行字段规则类方法
        const newModalFormData = FieldRuleClass.SetEncrypt(); //加密
        const { tableSelect } = dynamicStore;
        const { treeNode } = catalogStore;
        const stateNum: any = {
          Collect: 1,
          Arrangement: 2,
          Storage: 3,
          Utilization: 4
        };
        const param = {
          list: [
            {
              ...newModalFormData,
              Record_ID: global.createID(),
              FM_ID: route.query.fmid,
              FMT_ID: props.rollUpConfig.fmtData.filter((v: any) => v.FMT_ID === route.query.fmtid)[0].FMT_Parent_ID,
              Catalog_ID: dynamicStore.noCatalogStatus ? null : treeNode.Catalog_ID,
              Fonds_ID: route.query.fondsId,
              Status: stateNum[route.query.status]
            }
          ],
          tableName: tableName.value
        };
        vueAxios.post("Dynamic", param).then(async (res: any) => {
          cancel(); // 关闭弹框
          if (type === "modalFormData") {
            if (res.Mark) {
              for (let i = 0; i < tableSelect.length; i++) {
                const item = tableSelect[i];
                delete item.checkbox;
                await vueAxios
                  .put("Dynamic", {
                    list: [{ ...item, Parent_ID: res.List[0].Record_ID, Code: res.List[0].Code }],
                    tableName: dynamicStore.visibleConfig.FMT.FMT_TableName
                  })
                  .then((res2: any) => {
                    if (res2.Mark) {
                      const FieldRuleClass = new RuleClass({
                        modalFormData: res2.List[0],
                        ruleList: (ruleList.value = dynamicStore.visibleConfig.FieldRule.filter(
                          (v: any) => v.FR_Enable === true || v.FR_Rule.toLowerCase().includes("jm")
                        )),
                        tableName: dynamicStore.visibleConfig.FMT.FMT_TableName
                      }); // 执行字段规则类方法
                      FieldRuleClass.fieldRuleEvent2();
                      dynamicStore.updateTableData(res2.List[0]);
                    }
                  });
              }
            }
          }
        });
      };
      // 监听表单属性值的变化
      watch(
        modalFormData,
        (newVal, oldVal) => {
          let FieldRuleClass = null;
          FieldRuleClass = new RuleClass({
            modalFormData: newVal,
            ruleList: ruleList.value,
            tableName: tableName.value
          }); // 执行字段规则类方法
          FieldRuleClass.fieldRuleEvent2();
        },
        { immediate: true }
      );
      onMounted(() => {
        init();
      });
      return {
        modalFormData,
        ruleList,
        formRules,
        modalFormRef,
        submitLoading,
        submitLoading2,
        dictionary,
        continuousSubmission,
        transTree,
        init,
        cancel,
        onSubmit,
        onSubmit2,
        submitAnalyse
      };
    },
    template: props.rollUpConfig.htmlCode // 绑定模板
  });
  // 引入icon
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    currentApp.component(key, component);
  }
  // 挂载实例
  currentApp.use(ElementPlus, { locale: zhCn }).mount("#dynamic-form");
};

// 组件卸载时清理应用实例
onBeforeUnmount(() => {
  if (currentApp) {
    currentApp.unmount();
    currentApp = null;
  }
});

defineExpose({ open });
</script>
<style scoped lang="scss">
.dynamicForm {
  :deep(.previewModel) {
    .form_box {
      display: flex;
      max-height: calc(100vh - 95px);
      .form_left {
        width: 50%;

        // height: 100%;
        overflow-y: auto;
      }
      .form_right {
        width: 50%;

        // height: 100%;
        overflow-y: auto;
      }
      .el-date-editor {
        .el-input__wrapper {
          width: -webkit-fill-available;
        }
      }
    }
    .button {
      .el-form-item__content {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
  :deep(.el-dialog) {
    // top: 50%;
    margin-top: 0;

    // transform: translateY(-50%);
  }
  :deep(.el-overlay-dialog) {
    display: flex;
    align-items: center;
  }
  :deep(.el-dialog__body) {
    padding: 0;
  }
  #dynamic-form {
    // max-height: 65vh;
    padding: calc(var(--el-dialog-padding-primary)) var(--el-dialog-padding-primary);
    overflow: auto;
    .date {
      .el-input__wrapper {
        width: calc(100% - 22px);
      }
    }
  }
}
</style>
